package org.example;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferUShort;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CC_FileOutPut {

    public static void main(String[] args) throws IOException {
        String inputPngPath = "D:\\Documents\\workspaces\\Gitee\\java-projects\\untitled\\src\\main\\resources\\ame\\Snipaste.png";
        String outputRawPath = "output.raw";
        String outputPngPath = "output.png";

        // 步骤1: 读取PNG图片
        BufferedImage pngImage = ImageIO.read(new File(inputPngPath));

        // 步骤2: 转换PNG到16位黑白RAW
        convertToRaw16Grayscale(pngImage, outputRawPath);

        // 步骤3: 从RAW文件转成黑白PNG图片
        BufferedImage grayscalePng = convertFromRaw16Grayscale(outputRawPath, pngImage.getWidth(), pngImage.getHeight());

        // 步骤4: 使用ImageIO.write保存PNG图片
        ImageIO.write(grayscalePng, "png", new File(outputPngPath));
    }

    private static void convertToRaw16Grayscale(BufferedImage image, String outputPath) throws IOException {
        int width = image.getWidth();
        int height = image.getHeight();

        // 创建灰度图像
        BufferedImage grayscaleImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        grayscaleImage.getGraphics().drawImage(image, 0, 0, null);

        // 创建FileOutputStream对象
        try (FileOutputStream fos = new FileOutputStream(outputPath)) {
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int pixel = grayscaleImage.getRGB(x, y);
                    int luminance = (pixel & 0xff); // 灰度值
                    // 将8位灰度值扩展到16位
                    fos.write((luminance >>> 8) & 0xff);
                    fos.write(luminance & 0xff);
                }
            }
        }
    }

    private static BufferedImage convertFromRaw16Grayscale(String inputPath, int width, int height) throws IOException {
        byte[] rawData = new byte[width * height * 2];

        // 创建FileInputStream对象读取RAW数据
        try (FileInputStream fis = new FileInputStream(inputPath)) {
            int bytesRead = fis.read(rawData);
            if (bytesRead != width * height * 2) {
                throw new IOException("读取的RAW数据不完整.");
            }
        }

        // 创建16位灰度BufferedImage
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
        short[] pixelData = ((DataBufferUShort) image.getRaster().getDataBuffer()).getData();
        int dataIndex = 0;

        for (int i = 0; i < rawData.length; i += 2) {
            // 从两个连续的字节中构造16位灰度值
            pixelData[dataIndex++] = (short) ((rawData[i] << 8) | (rawData[i + 1] & 0xff));
        }

        return image;
    }
}
